<template>
	<div>
		<div id="container"></div>
	</div>
</template>

<script>
// 安装three.js  cnpm install --save three 
import * as THREE from 'three'

// http://www.yanhuangxueyuan.com/Three.js/
// https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene

export default {
	data() {
		return {
			camera: null,
			scene: null,
			renderer: null,
			mesh: null
		}
	},
	mounted() {
		this.init()
		// this.renderer.render(this.scene, this.camera)
		this.animate()
		// setInterval(() => {
		// 	this.mesh.rotation.x += 0.01
		// 	this.mesh.rotation.y += 0.01
		// 	// 将相机和场景加入到渲染器中
		// 	this.renderer.render(this.scene, this.camera)
		// }, 40)
	},
	methods: {
		init() {
			let container = document.getElementById('container')
				
			// 创建相机  相机相当于人眼观从某个位置去观察物体  透视投影相机(看物体会有近大远小的透视关系)  还有一种相机是正交相机，没有透视关系
			// https://threejs.org/docs/index.html?q=cam#api/en/cameras/Camera
			this.camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 10, 10000)
			this.camera.position.x = 20
			this.camera.position.y = 10
			this.camera.position.z = 20
			
			// 设置几何体
			// https://threejs.org/docs/index.html?q=geometry#api/en/geometries/BoxGeometry
			let geometry = new THREE.BoxGeometry(2, 2, 2)
			// 设置材质
			// https://threejs.org/docs/index.html?q=material#api/en/constants/Materials
			// https://threejs.org/docs/index.html?q=material#api/zh/materials/MeshNormalMaterial
			let material = new THREE.MeshNormalMaterial()
			// https://threejs.org/docs/index.html?q=Mesh#api/en/objects/Mesh
			this.mesh = new THREE.Mesh(geometry, material)
			
			// 设置场景
			// https://threejs.org/docs/index.html?q=scene#api/en/scenes/Scene
			this.scene = new THREE.Scene()
			// 将物体加入到场景中
			this.scene.add(this.mesh)
			// http://www.yanhuangxueyuan.com/doc/three.js/lookat.html
			this.camera.lookAt(this.scene.position)
			// 设置渲染器
			// https://threejs.org/docs/index.html?q=WebGLRenderer#api/en/renderers/WebGLRenderer
			this.renderer = new THREE.WebGLRenderer({
				antialias: true
			})
			// 设置渲染范围尺寸
			this.renderer.setSize(container.clientWidth, container.clientHeight)
			// this.renderer.setSize(container.clientWidth / 2, container.clientHeight / 2)
			
			// 添加辅助线
			var axes = new THREE.AxesHelper(20);
			this.scene.add(axes);
			
			// 将渲染器加入到dom节点中
			container.appendChild(this.renderer.domElement)			
		},
		animate() {
			requestAnimationFrame(this.animate)
			this.mesh.rotation.x += 0.01
			this.mesh.rotation.y += 0.02
			this.renderer.render(this.scene, this.camera)
		}
	}
}
/* 
	three.js是右手坐标系，z轴正方向对着开发者
	3d开发涉及到几个东西，相机、场景、渲染器
*/
</script>

<style scoped>
#container {
    height: 100vh;
}
</style>
